package com.platform.cdcs.fragment.detail;

import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.platform.cdcs.R;
import com.platform.cdcs.model.BaseObjResponse;
import com.platform.cdcs.model.InvoiceList;
import com.platform.cdcs.model.MockObj;
import com.platform.cdcs.model.ProductList;
import com.platform.cdcs.tool.Constant;
import com.sherchen.slidetoggleheader.views.ObservableXListView;
import com.sherchen.slidetoggleheader.views.XListView;
import com.trueway.app.uilib.adapter.EnhancedAdapter;
import com.trueway.app.uilib.fragment.BaseFragment;
import com.trueway.app.uilib.tool.Utils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 * Created by holytang on 2017/11/3.
 */
public class InOutTicketFragment extends BaseFragment {

    private ObservableXListView listView;
    private ItemAdapter adapter;
    private int pageIndex = 1;
    private int type;
    private ProductList.ProductItem item;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type = getArguments().getInt("type", 0);
        if (type == 0) {
            item = (ProductList.ProductItem) getArguments().getSerializable("model");
        }
    }

    @Override
    public void initView(View view) {
        adapter = new ItemAdapter(getContext());
        initLoadImg(view.findViewById(R.id.load));
        hideThisToolBar(view);
        getToolBar().setNavigationIcon(R.mipmap.icon_back);
        getToolBar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getActivity().finish();
            }
        });
        if (type == 1) {
            setTitle("发货方出库单");
        } else {
            setTitle("出入库单");
        }
        listView = (ObservableXListView) view.findViewById(android.R.id.list);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //详情页面
                i = i - 1;
            }
        });
        listView.setAdapter(adapter);
        if (type != 1) {
            listView.setXListViewListener(new XListView.IXListViewListener() {
                @Override
                public void onRefresh() {
                    pageIndex = 1;
                    adapter.clear();
                    adapter.notifyDataSetChanged();
                    requestList(false);
                }

                @Override
                public void onLoadMore() {
                    requestList(false);
                }
            });
            listView.setPullRefreshEnable(true);
            requestList(true);
        } else {
            listView.setPullRefreshEnable(false);
            requestInfo();
        }
    }

    private void requestList(boolean flag) {
        if (flag) {
            showLoadImg();
        }
        Map<String, String> param = new HashMap<>();
        param.put("productId", item.getProductId());
        param.put("cusName", item.getCusName());
        param.put("distName", item.getDistName());
        param.put("serialNumber", item.getSerialNumber());
        param.put("inNO", "");
        param.put("pageIndex", String.valueOf(pageIndex));
        param.put("pageSize", String.valueOf(Constant.PAGE_SIZE));

        getHttpClient().post().url(Constant.OUT_HOUSELIST).params(Constant.makeParam(param)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                listView.stopRefresh();
                listView.stopLoadMore();
                Utils.showToast(getActivity(), R.string.server_error);

            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    if(getContext()==null){
                        return;
                    }
                    dismissLoadImg();
                    listView.stopRefresh();
                    listView.stopLoadMore();
                }catch (Exception e){

                }
            }
        });
    }

    @Override
    public int layoutId() {
        return R.layout.listview;
    }

    private void requestInfo() {
        showLoadImg();
        Map<String, String> param = new HashMap<>();
        param.put("docNo", getArguments().getString("id"));
        getHttpClient().post().url(Constant.DIST_DOCUMENT_INFO).params(Constant.makeParam(param)).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int i) {
                dismissLoadImg();
                Utils.showToast(getContext(), R.string.server_error);
            }

            @Override
            public void onResponse(String s, int i) {
                try {
                    if (getContext() == null) {
                        return;
                    }
                    dismissLoadImg();
                    Type type = new TypeToken<BaseObjResponse<DocumentInfo>>() {
                    }.getType();
                    BaseObjResponse<DocumentInfo> response = new Gson().fromJson(s, type);
                    if ("1".equals(response.getResult().getCode())) {
                        adapter.addItem(response.getResult().getDocumentInfo());
                        adapter.notifyDataSetChanged();
                    } else {
                        Utils.showToast(getContext(), response.getResult().getMsg());
                    }
                } catch (Exception e) {
                }
            }
        });
    }

    private class ItemAdapter extends EnhancedAdapter<InvoiceList.Invoice> {

        public ItemAdapter(Context context) {
            super(context);
        }

        @Override
        protected void bindView(View paramView, Context paramContext, int position) {
            InvoiceList.Invoice invoice = getItem(position);
            ViewHolder holder = (ViewHolder) paramView.getTag();
            holder.title1.setText(invoice.getDistName());
            holder.text1.setText(invoice.getDistCode());
            if ("1".equals(invoice.getDocType())) {
                holder.typeView.setText("退货入库");
                holder.typeView.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_in, 0, 0, 0);
            } else {
                holder.typeView.setText("退货出库");
                holder.typeView.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.icon_out, 0, 0, 0);
            }
            holder.title2.setText(invoice.getCusName());
            holder.text2.setText(invoice.getCusCode());
            holder.title3.setText(invoice.getDocNo());
            holder.text3.setText(invoice.getDocDate());

        }

        @Override
        protected View newView(Context context, int position, ViewGroup viewgroup) {
            View rootView = inflater.inflate(R.layout.inout_ticket_item, viewgroup, false);
            ViewHolder holder = new ViewHolder();
            holder.title1 = (TextView) rootView.findViewById(R.id.title);
            holder.text1 = (TextView) rootView.findViewById(R.id.title1);
            holder.typeView = (TextView) rootView.findViewById(R.id.title2);
            holder.title2 = (TextView) rootView.findViewById(R.id.title3);
            holder.text2 = (TextView) rootView.findViewById(R.id.text);
            holder.title3 = (TextView) rootView.findViewById(R.id.text1);
            holder.text3 = (TextView) rootView.findViewById(R.id.text2);
            rootView.setTag(holder);
            return rootView;
        }
    }

    private class ViewHolder {
        TextView title1, text1, typeView, title2, text2, title3, text3;
    }

    private class DocumentInfo extends MockObj {

        private InvoiceList.Invoice documentInfo;

        public InvoiceList.Invoice getDocumentInfo() {
            return documentInfo;
        }

        public void setDocumentInfo(InvoiceList.Invoice documentInfo) {
            this.documentInfo = documentInfo;
        }
    }
}
